package com.logicwin.aibala.ui.screens.screenmain;

import com.logicwin.aibala.Main;
import com.logicwin.aibala.R;
import com.logicwin.aibala.detailPackActivity.testActivity;
import com.logicwin.aibala.model.androidSWInfo.AndroidSWInfoService;
import com.logicwin.aibala.ui.screens.Screen;

import android.util.Log;
import android.view.GestureDetector.OnGestureListener;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.provider.ContactsContract.CommonDataKinds.Event;
import android.view.GestureDetector;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.animation.AnimationUtils;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.HorizontalScrollView;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.ViewFlipper;
import android.widget.AbsListView.OnScrollListener;


public class ScreenHome  extends Screen  implements OnTouchListener, OnGestureListener{
/*	private ApkPackageAdapter mHomeAdapter;*/
	private static String TAG = Main.class.getCanonicalName();
	
	private final int BTN_MAIN 			= 0;
	private final int BTN_GAMES		 	= 1;
	private final int BTN_ENTERTAINMENT = 2;
	private final int BTN_SOCIALITY 	= 3;
	private final int BTN_LIFE 			= 4;
	private final int BTN_BUSINESS  	= 5;	
	private final int BTN_SYSTEM 		= 6;
	
	private final int MENU_BTN_CONFIG 	= 0;
	private final int MENU_BTN_DOWNLOAD = 1;
	private final int MENU_BTN_MESSAGE 	= 2;
	private final int MENU_BTN_REFRESH 	= 3;
	private final int MENU_BTN_SEARCH 	= 4;
	
	private GestureDetector mGestureDetector;
	private int mCurrIndex = 0;
	
	private ViewFlipper mViewFlipper;
	private HorizontalScrollView mNavigateButtons;
	private ImageButton mButton_Home;
	private ImageButton mButton_Games;
	private ImageButton mButton_Business;
	private ImageButton mButton_Life;
	private ImageButton mButton_Sociality;
	private ImageButton mButton_System;
	private ImageButton mButton_Entertainment;
	
	private Context mContext;
	private ListView mListHome;
	private Handler mHandler = new Handler();
	
	public ScreenHome() {
		super(SCREEN_TYPE.HOME_T, ScreenHome.class.getCanonicalName());
		// TODO Auto-generated constructor stub
	}

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.screen_home); 
		try{
			InitViewFlipper();
			InitScrollViewButton();
			mContext = this;
		}
		catch(Exception e)
		{
			Log.i("ScreenHome", e.toString());
		}
	}
    private AdapterView.OnItemClickListener clictlistener = new AdapterView.OnItemClickListener() {     
        @Override  
        public void onItemClick(AdapterView<?> arg0, View arg1, int position,   
                long arg3) {   
    		Intent intent = new Intent(mContext,testActivity.class);
    		intent.putExtra("resId", R.drawable.sw1);
    		startActivity(intent);
               Log.i("ScreenHome", "clictlistener"+position);
        }   
    };	
	private void setListView(ListView view, ListViewScrollListener listener,  
				ApkPackageAdapter adapter){
		view.setAdapter(adapter);
		view.setOnItemClickListener(adapter);
		//view.setOnItemClickListener(clictlistener);
		view.setOnScrollListener(listener);		
	}
	
	private void InitViewFlipper(){
		mNavigateButtons = (HorizontalScrollView)findViewById(R.id.navigate_view);
		
        mViewFlipper = (ViewFlipper)findViewById(R.id.flipper); 
       	
        ListView listhome = (ListView) findViewById(R.id.listview_home);  
        mListHome = listhome;
        setListView(listhome,new ListViewScrollListener(BTN_MAIN),new ApkAdapterHome(this,
        		AndroidSWInfoService.getHotList(AndroidSWInfoService.CLASS_ID_GAME)) );
        
        ListView listgames = (ListView) findViewById(R.id.listview_games);
        ApkAdapterGames adapterGames = new ApkAdapterGames(this,
        		AndroidSWInfoService.getHotList(AndroidSWInfoService.CLASS_ID_GAME));
        setListView(listgames,new ListViewScrollListener(BTN_GAMES),adapterGames);
        
        ListView listentertainment = (ListView) findViewById(R.id.listview_entertainment);
        ApkAdapterEntertainment adapterEntertainment = new ApkAdapterEntertainment(this,
        		AndroidSWInfoService.getHotList(AndroidSWInfoService.CLASS_ID_OFFICE));
        setListView(listentertainment, new ListViewScrollListener(BTN_ENTERTAINMENT), 
        		adapterEntertainment);
        
        ListView listsociality = (ListView) findViewById(R.id.listview_sociality);
        ApkAdapterSociality adapterSociality = new ApkAdapterSociality(this,
        		AndroidSWInfoService.getHotList(AndroidSWInfoService.CLASS_ID_NETWORKING));
        setListView(listsociality,new ListViewScrollListener(BTN_SOCIALITY),adapterSociality);
        
        ListView listlife = (ListView) findViewById(R.id.listview_life);
        ApkAdapterLife adapterLife = new ApkAdapterLife(this,
        		AndroidSWInfoService.getHotList(AndroidSWInfoService.CLASS_ID_LIFE));
        setListView(listlife, new ListViewScrollListener(BTN_LIFE), adapterLife);
        
        ListView listbusiness = (ListView) findViewById(R.id.listview_business);
        setListView(listbusiness, new ListViewScrollListener(BTN_BUSINESS), new ApkAdapterBusiness(this,
        		AndroidSWInfoService.getHotList(AndroidSWInfoService.CLASS_ID_UTIL)));
        
        ListView listsystem = (ListView) findViewById(R.id.listview_system);
        setListView(listsystem,new ListViewScrollListener(BTN_SYSTEM), new ApkAdapterBusiness(this,
        		AndroidSWInfoService.getHotList(AndroidSWInfoService.CLASS_ID_VIDEO)));
       
        mGestureDetector = new GestureDetector(this);
        
        setGestureListener(mViewFlipper);
        setGestureListener(listhome);
      
        setGestureListener(listgames); 	
        setGestureListener(listentertainment); 
        setGestureListener(listsociality); 
        setGestureListener(listlife);
        setGestureListener(listbusiness);
        setGestureListener(listsystem);        
	}
	
	private void setGestureListener(View v){
		v.setOnTouchListener(this);
		/*
		v.setOnTouchListener(new OnTouchListener(){
        	public boolean onTouch(View v, MotionEvent event){        		
        		mGestureDetector.onTouchEvent(event);
        		return false;
        	}
        });
        */
	}

	public boolean onTouch(View v, MotionEvent event) {
		// TODO Auto-generated method stub
		return mGestureDetector.onTouchEvent(event); 
	}

	public boolean onDown(MotionEvent e) {
		// TODO Auto-generated method stub
		return true;
	}

	public void onShowPress(MotionEvent e) {
		// TODO Auto-generated method stub
		
	}

	public boolean onSingleTapUp(MotionEvent e) {
		// TODO Auto-generated method stub
		return false;
	}

	public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
			float distanceY) {
		// TODO Auto-generated method stub
		return false;
	}

	public void onLongPress(MotionEvent e) {
		// TODO Auto-generated method stub
		
	}
	
	class  ScrollClickListener implements OnClickListener{
		
		public ScrollClickListener(int index){mIdex = index;}
		
		public void onClick(View v) {
			SetButtonImage(mCurrIndex,false);
			mCurrIndex = mIdex;
			SetButtonImage(mCurrIndex,true);
			mViewFlipper.setDisplayedChild(mIdex);
		}		
		private int mIdex;
	};		
	
	private void InitScrollViewButton(){
		mButton_Home = (ImageButton) this.findViewById(R.id.button_homepage);
		mButton_Home.setOnClickListener(new ScrollClickListener(BTN_MAIN));		
		
		mButton_Games = (ImageButton) this.findViewById(R.id.button_games);
		mButton_Games.setOnClickListener(new ScrollClickListener(BTN_GAMES));
		
		mButton_Entertainment = (ImageButton) this.findViewById(R.id.button_entertainment);
		mButton_Entertainment.setOnClickListener(new ScrollClickListener(BTN_ENTERTAINMENT));	
		
		mButton_Sociality = (ImageButton) this.findViewById(R.id.button_sociality);
		mButton_Sociality.setOnClickListener(new ScrollClickListener(BTN_SOCIALITY));
		
		mButton_Life = (ImageButton) this.findViewById(R.id.button_life);
		mButton_Life.setOnClickListener(new ScrollClickListener(BTN_LIFE));
		
		mButton_Business = (ImageButton) this.findViewById(R.id.button_business);
		mButton_Business.setOnClickListener(new ScrollClickListener(BTN_BUSINESS));
				
		mButton_System = (ImageButton) this.findViewById(R.id.button_system);
		mButton_System.setOnClickListener(new ScrollClickListener(BTN_SYSTEM));	
		
		mNavigateButtons = (HorizontalScrollView) this.findViewById(R.id.navigate_view);
		mNavigateButtons.setSmoothScrollingEnabled(true);
		SetButtonImage(mCurrIndex, true);
		
	}
	private void showNext(){	
		SetButtonImage(mCurrIndex,false);
		this.mCurrIndex ++;
		SetButtonImage(mCurrIndex,true);		
		if(mCurrIndex >= BTN_LIFE)
			mHandler.post(new Runnable(){
				@Override
				public void run() {
					// TODO Auto-generated method stub
					mNavigateButtons.smoothScrollTo(mNavigateButtons.getRight(), mNavigateButtons.getBottom());
				}		
			});
			
		mViewFlipper.showNext();
	}
	public boolean haveMenu(){
		return true;
	}	
	public boolean createOptionsMenu(Menu menu){	
		MenuItem itemConfig = menu.add(0, MENU_BTN_CONFIG, 0, "config").setIcon(R.drawable.topbutton_configure);
		MenuItem itemDownload = menu.add(0, MENU_BTN_DOWNLOAD, 0, "download").setIcon(R.drawable.topbutton_download);
		MenuItem itemMessage = menu.add(0, MENU_BTN_MESSAGE, 0, "message").setIcon(R.drawable.topbutton_message);
		MenuItem itemRefresh = menu.add(1, MENU_BTN_REFRESH, 0, "refresh").setIcon(R.drawable.topbutton_refresh);
		MenuItem itemSearch = menu.add(1, MENU_BTN_SEARCH, 0, "search").setIcon(R.drawable.topbutton_search);
		itemConfig.setEnabled(true);
		itemDownload.setEnabled(true);
		itemMessage.setEnabled(true);
		itemRefresh.setEnabled(true);
		itemSearch.setEnabled(true);
		return true;
	}
	public boolean onOptionsItemSelected(MenuItem item) {
		switch(item.getItemId()){
		case MENU_BTN_CONFIG:
			Log.i(TAG,"onOptionsItemSelected, MENU_BTN_CONFIG clicked.");
			break;
		case MENU_BTN_DOWNLOAD:
			Log.i(TAG,"onOptionsItemSelected, MENU_BTN_DOWNLOAD clicked.");
			break;
		case MENU_BTN_MESSAGE:
			Log.i(TAG,"onOptionsItemSelected, MENU_BTN_MESSAGE clicked.");
			break;
		case MENU_BTN_REFRESH:
			Log.i(TAG,"onOptionsItemSelected, MENU_BTN_REFRESH clicked.");
			break;
		case MENU_BTN_SEARCH:
			Log.i(TAG,"onOptionsItemSelected, MENU_BTN_SEARCH clicked.");
			break;
		default:
			break;
		}
		return true;
	}
	private void showPrev(){
		SetButtonImage(mCurrIndex,false);
		this.mCurrIndex --;
		if(mCurrIndex < BTN_LIFE)
			mHandler.post(new Runnable(){
				@Override
				public void run() {
					// TODO Auto-generated method stub
					mNavigateButtons.smoothScrollTo(mNavigateButtons.getLeft(), mNavigateButtons.getBottom());
				}		
			});			
		//	mNavigateButtons.smoothScrollTo(mNavigateButtons.getLeft(), mNavigateButtons.getBottom());
		SetButtonImage(mCurrIndex,true);	
		mViewFlipper.showPrevious();
	}
	
	private void SetButtonImage(int index, boolean isPressed){
		switch(index)
		{
		case BTN_MAIN:
			if(isPressed) 	mButton_Home.setImageResource(R.drawable.word_homepageon);
			else	      	mButton_Home.setImageResource(R.drawable.word_homepage);	
			break;
			
		case BTN_GAMES:
			if(isPressed) 	mButton_Games.setImageResource(R.drawable.word_gameson);
			else			mButton_Games.setImageResource(R.drawable.word_games);
			break;
			
		case BTN_ENTERTAINMENT:
			if(isPressed)	mButton_Entertainment.setImageResource(R.drawable.word_yuleon);
			else			mButton_Entertainment.setImageResource(R.drawable.word_yule);
			break;
			
		case BTN_SOCIALITY:
			if(isPressed)	mButton_Sociality.setImageResource(R.drawable.word_networkon);
			else			mButton_Sociality.setImageResource(R.drawable.word_network);			
			break;
			
		case BTN_LIFE:
			if(isPressed)	mButton_Life.setImageResource(R.drawable.word_liveon);
			else			mButton_Life.setImageResource(R.drawable.word_live);
			break;
			
		case BTN_BUSINESS:
			if(isPressed)	mButton_Business.setImageResource(R.drawable.word_businesson);
			else			mButton_Business.setImageResource(R.drawable.word_business);			
			break;
			
		case BTN_SYSTEM:
			if(isPressed)	mButton_System.setImageResource(R.drawable.word_systemon);
			else			mButton_System.setImageResource(R.drawable.word_system);			
			break;
			
		default:
			break;
		}
		
	}
	public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
			float velocityY) {
		// TODO Auto-generated method stub
		final int FLING_MIN_DISTANCE = 150, FLING_MIN_VELOCITY = 250;  
		if (e1.getX() - e2.getX() > FLING_MIN_DISTANCE
				&& Math.abs(velocityX) > FLING_MIN_VELOCITY) {
	        mViewFlipper.setInAnimation(AnimationUtils.loadAnimation(getApplicationContext(), 
	        		R.anim.push_left_in));
	        mViewFlipper.setOutAnimation(AnimationUtils.loadAnimation(getApplicationContext(), 
	        		R.anim.push_left_out));	
	       
	        if (mViewFlipper.getCurrentView().getId() != R.id.flipper_system)
	        	showNext();	      

		} else if (e2.getX() - e1.getX() > FLING_MIN_DISTANCE
				&& Math.abs(velocityX) > FLING_MIN_VELOCITY) {
	        mViewFlipper.setInAnimation(AnimationUtils.loadAnimation(getApplicationContext(), 
	        		R.anim.push_right_in));
	        mViewFlipper.setOutAnimation(AnimationUtils.loadAnimation(getApplicationContext(), 
	        		R.anim.push_right_out)); 			

	        if(mViewFlipper.getCurrentView().getId() != R.id.flipper_home)
	        	showPrev();
		}		
		return false;
	}	
/*	private void ShowScreen(){
		
	}*/
	class ListViewScrollListener implements OnScrollListener{

		private final int mnInterval = 3;
		private int mType;
		public ListViewScrollListener(int type){
			mType = type;			
		}
		@Override
		public void onScrollStateChanged(AbsListView view, int scrollState) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onScroll(AbsListView view, int firstVisibleItem,
				int visibleItemCount, int totalItemCount) {
			// TODO Auto-generated method stub
			if(firstVisibleItem + visibleItemCount < totalItemCount - mnInterval)
				return;
			switch(mType){
			
			case BTN_MAIN:
				break;
			case BTN_GAMES:
				break;
			case BTN_BUSINESS:
				break;
			case BTN_LIFE:
				break;
			case BTN_SOCIALITY:
				break;
			case BTN_SYSTEM:
				break;
			case BTN_ENTERTAINMENT:
				break;
			default:
				break;
			}
			
		}

	}

}
